<?php
declare(strict_types=1);

namespace App\Core;

final class Config
{
    /** @var array<string,string> */
    private static array $data = [];
    private static bool $loaded = false;

    public static function load(?string $path = null): void
    {
        if (self::$loaded) {
            return;
        }
        $path = $path ?? (defined('APP_ROOT') ? APP_ROOT . '/.env' : (__DIR__ . '/../../.env'));
        if (is_file($path) && is_readable($path)) {
            $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || str_starts_with($line, '#')) {
                    continue;
                }
                $pos = strpos($line, '=');
                if ($pos === false) {
                    continue;
                }
                $key = trim(substr($line, 0, $pos));
                $val = trim(substr($line, $pos + 1));
                $val = self::stripQuotes($val);
                self::$data[$key] = $val;
            }
        }
        self::$loaded = true;
    }

    public static function get(string $key, ?string $default = null): ?string
    {
        if (!self::$loaded) {
            self::load();
        }
        return self::$data[$key] ?? $default;
    }

    public static function set(string $key, string $value): void
    {
        self::$data[$key] = $value;
    }

    private static function stripQuotes(string $val): string
    {
        if ($val === '') return $val;
        if (($val[0] === '"' && substr($val, -1) === '"') || ($val[0] === "'" && substr($val, -1) === "'")) {
            return substr($val, 1, -1);
        }
        return $val;
    }
}